#include"MemoryPool.h"
#include<vector>
template <class T, int BlockSize>
MemoryPool<T, BlockSize>::MemoryPool()
{
     this->MemoryHead=nullptr;
     this->UseHead=nullptr;

     this->head=0;
     this->use=0;
}
template <typename T, int BlockSize>
MemoryPool<T, BlockSize>::~MemoryPool()
{
    _Node<T>* ptr;
	while (this->MemoryHead)
	{
		ptr = this->MemoryHead->next;
		delete this->MemoryHead;
		MemoryHead = ptr;
	}
    
     _Node<T>* ptr1;
	while (this->UseHead)
	{
		ptr1 = this->UseHead->next;
		delete this->UseHead;
		UseHead = ptr1;
	}

}
template <class T, int BlockSize>
void* MemoryPool<T, BlockSize>::MemoryPoolMalloc()
{
    if(this->MemoryHead==nullptr){
        //当没有空闲节点
        this->MemoryHead=new _Node<T>;
        _Node<T>*temp=this->MemoryHead;   //将数据连接起来
        for(int i=1;i<BlockSize;i++){
             temp->next=new _Node<T>;
             temp=temp->next;
        }
        temp->next=nullptr;
        
        this->head+=BlockSize;
    }
    _Node<T>* temp=MemoryHead;
    this->add=temp;
    MemoryHead=MemoryHead->next;;  //指向下一个数据节点
    //将data 挂在到UseHead
    temp->next=UseHead;
    UseHead=temp;
    this->head--;
    this->use++;
    return reinterpret_cast<void*>(temp);
}

template <typename T, int BlockSize>
int MemoryPool<T, BlockSize>::MemoryPoolFree(void*p)
{
     //遍历 UseHead链表
    _Node<T>*p1=(_Node<T>*)p; 
    _Node<T>*temp=UseHead;
    _Node<T>*prev;
    if(temp==p1){  //第一个就是
      _Node<T>*temp1=temp;
      UseHead=UseHead->next;
      temp1->next=MemoryHead;   //将节点重新接到MemoryHead
      MemoryHead=temp1;
      this->use--;
      this->head++;
      return 1;
    }
    while(temp!=nullptr){
        if(temp==p1){    
            _Node<T>*temp1=temp;
            prev->next=temp->next;
            temp1->next=MemoryHead;
            MemoryHead=temp1;
             this->use--;
             this->head++;
            return 1;
        }
        prev=temp;
        temp=temp->next;
    }  
    return -1;
}

int main(){
    MemoryPool<int,100>pa;
    vector<int*>ret;
    for(int i=0;i<50;i++){
        ret.push_back(reinterpret_cast<int*>(pa.MemoryPoolMalloc()));
    }
    cout<<"head:"<<pa.head<<"use:"<<pa.use<<endl;
    for(int i=0;i<10;i++){
        pa.MemoryPoolFree(reinterpret_cast<void*>(ret[i]));
    }
    cout<<"head:"<<pa.head<<"use:"<<pa.use<<endl;
    return 0;
}